package com.dong.design.singleton;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 单例模式——懒汉模式
 * 是否 Lazy 初始化：是
 * 是否多线程安全：否
 * 实现难度：易
 * 描述：这种方式是最基本的实现方式，这种实现最大的问题就是不支持多线程。
 * 因为没有加锁 synchronized，所以严格意义上它并不算单例模式。
 * 这种方式 lazy loading 很明显，不要求线程安全，在多线程不能正常工作。
 *
 * @author jianyang206881
 * @date 2018/2/24
 */
public class LazySingleton {
    private static LazySingleton instance;

    private LazySingleton() {

    }

    public static synchronized LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }

    public static void main(String[] args) throws InterruptedException {

        /*
         * <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
         <dependency>
         <groupId>org.apache.commons</groupId>
         <artifactId>commons-lang3</artifactId>
         <version>3.3.2</version>
         </dependency>
         */
        ThreadFactory namedThreadFactory = new BasicThreadFactory.Builder()
                .namingPattern("lazy-singleton-pool-%d").daemon(true).build();

        ThreadPoolExecutor singlePool = new ThreadPoolExecutor(3, 10,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(2), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

        for (int i = 0; i < 20; i++) {
            singlePool.execute(() -> {
                LazySingleton newInstance = LazySingleton.getInstance();
                System.out.println(Thread.currentThread().getName() + ":" + newInstance + "-" + Thread.activeCount());
            });
        }

        singlePool.shutdown();

    }

}
